<template>
  <div class="box">
    <div class="left">
      <div class="Ltitle">
        <span>试卷分类</span>
      </div>
      <div class="Lline"></div>
      <div class="Ltree">
        <el-tree
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          :highlight-current="true"
          :expand-on-click-node="true"
          :default-expand-all="false"
          :auto-expand-parent="false"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span style="margin-right: 15px">{{ node.label }}</span>
          </span>
        </el-tree>
      </div>
    </div>
    <div class="right">
      <div class="RForm">
        <el-form ref="form" :inline="true" :model="queryParams" v-if="rolesId.includes(1)||rolesId.includes(2)">
          <el-form-item>
            <el-select
              v-model="queryParams.userId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId"
              >
              </el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item>-->
<!--            <el-input-->
<!--              placeholder="标题"-->
<!--              size="mini"-->
<!--              v-model="queryParams.name"-->
<!--            ></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item>-->
<!--            <el-input-->
<!--              placeholder="标题"-->
<!--              size="mini"-->
<!--              v-model="queryParams.name"-->
<!--            ></el-input>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" size="mini" icon="el-icon-search" @click="getTableData"
              >搜索</el-button
            >
<!--            {{rolesId}}{{rolesId.includes(1)||rolesId.includes(2)}}-->
          </el-form-item>
        </el-form>
      </div>

      <div class="rBottom">
        <el-collapse accordion>
          <el-collapse-item
            v-for="item in tableData"
            :key="item.errorTestPaperId"
            style="margin-bottom: 20px; min-height: max-content"
          >
            <template slot="title">
              <div class="rItemLeft">
                <div>创建人：{{ item.sysUser.nickName }}</div>
                <div>创建于：{{ item.createTime }}</div>
              </div>

              <div
                :class="`${
                  item.learningStatistics.result == '错误'||item.learningStatistics.result == 'no'
                    ? 'yesOrNo'
                    : 'yesOrNo1'
                }`"
              >
                {{ item.learningStatistics.result }}
              </div>

              <el-button type="text" v-if="rolesId.includes(1)" class="deleBtn" @click.stop="deleTable(item)">删除</el-button>

            </template>
            <div class="itemBottom">
              <el-image
                style="height: 100%; width: 100%"
                fit="contain"
                :id="`${item.errorTestPaperId}|img`"
                :preview-src-list="[
                  setHttps(item.learningStatistics.pictureAddress),
                ]"
                :src="setHttps(item.learningStatistics.pictureAddress)"
              >
              </el-image>
              <!-- {{ setBase64(`${item.errorTestPaperId}|img`, item) }} -->
              <!-- {{ item.learningStatistics.pictureAddress }}
              {{ setHttps(item.learningStatistics.pictureAddress) }} -->

              <el-button
                class="previewBtn"
                type="text"
                @click="goPreviewView(item)"
                ><i class="el-icon-view"></i> 查看推荐题目</el-button
              >
              <!-- <el-button
                class="previewBtn"
                type="text"
                style="top: 40px"
                @click="goAddBank(item)"
                ><i class="el-icon-view"></i> 添加到题库</el-button
              > -->
            </div>
          </el-collapse-item>
        </el-collapse>

      </div>
      <div style="height: 60px">
        <pagination
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getTableData"
        />
      </div>
    </div>
  </div>
</template>
<script>
import {delTable, listTypes} from "@/api/questionBank/type.js";
import { getWrongQuestionList } from "@/api/studentEnd/analysisOfTheStudents";
import {mapGetters} from "vuex";
import {listUser} from "@/api/system/user";
export default {
  data() {
    return {
      treeData: [],

      defaultProps: {
        children: "children",
        label: "name",
        val: "id",
      },
      tableData: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        learningStatistics: null,
      },
      total: 0,
      totalQuantity: 0,
      clickHandler: null, // 存储事件处理函数的引用
      mdata: null,
      oldBankId: "",
      userList: [],
    };
  },

  mounted() {
    this.getTreeList();
    this.getTableData();
    this.getUserList();
  },
  computed: {
    ...mapGetters(["screenSize", "permissions", "rolesId", "userId","typeScreen"])
  },
  watch: {},

  methods: {
    setHttps(val) {
      let http = val.split("://")[1];
      if (val.split("://")[0] == "http") {
        return `https://${http}`;
      } else {
        return val;
      }
    },

    getToken() {
      return getToken();
    },

    getTreeList() {
      let arr = [
        {
          name: "题型辨识",
          type: 999,
          index: 5,
          children: [],
        },
        {
          name: "条件翻译",
          type: 999,
          index: 8,
          children: [],
        },
        {
          name: "计算",
          type: 999,
          index: 9,
          children: [],
        },
      ];

      for (let i = 0; i < arr.length; i++) {
        listTypes({ reserve3: arr[i].index }).then((Response) => {
          if (Response.code == 200) {
            arr[i].children = Response.rows;
          }
        });
      }
      console.log(arr, "4545");
      this.treeData = arr;
    },
    //点击树状图
    handleNodeClick(val) {
      // console.log(val);
      let obj = {
        topicTag: val.id,
      };
      // this.queryParams.learningStatistics=JSON.stringify(obj)
      this.queryParams["learningStatistics.topicTag"] = val.id;
      this.getTableData();
    },
    async  getUserList() {
      let obj = {
        pageSize: 999,
        pageNum: 1,
      };
      await  listUser(obj).then((res) => {
        if (res.code == 200) {
          this.userList = res.rows;
        }
      });
    },
    getTableData() {
      console.log(this.queryParams);
      getWrongQuestionList(this.queryParams).then((res) => {
        this.tableData = res.rows;
        this.total = res.total;
        this.totalQuantity = res.totalQuantity;
        this.tableData.forEach((ele) => {
          ele["base64"] = null;
        });
      });
    },
    //预览按钮
    goPreviewView(val) {
      this.$router.push(
        "/studentEnd/studentEnd/analysisOfTheStudents/wrongQuestion?examinationPaperSummaryId=" +
          val.errorTestPaperId
      );
    },
    //添加题目
    goAddBank(item) {
      console.log(item.learningStatistics.pictureAddress);

      let img = new Image();
      img.crossOrigin = "Anonymous"; // 设置跨域属性

      img.onload = function () {
        let canvas = document.createElement("canvas");
        canvas.width = this.width;
        canvas.height = this.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(this, 0, 0, this.width, this.height);

        try {
          let base64 = canvas.toDataURL("image/jpeg");
          console.log(base64);
        } catch (e) {
          console.error("导出图片时出错：", e);
        }
      };

      img.onerror = function () {
        console.error("图片加载失败");
      };

      img.src = item.learningStatistics.pictureAddress;
    },
    setBase64(id, item) {
      console.log(id, item, "item");

      setTimeout(() => {
        let img = document.getElementById(id);
        console.log(img);
        let canvas = document.createElement("canvas");
        // canvas.width = this.width;
        // canvas.height = this.height;
        canvas.width = img.width;
        canvas.height = img.height;
        console.log(img.width, img.height, "宽高");
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);

        try {
          let base64 = canvas.toDataURL("image/jpeg");
          console.log(base64);
        } catch (e) {
          console.error("导出图片时出错：", e);
        }
      }, 300);
    },

    //删除数据
    deleTable(item){
      console.log(item)
      this.$confirm('确认删除这条数据吗？', '提示').then(()=>{
        delTable(item.errorTestPaperId).then(res=>{
          if(res.code==200){
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getTableData()
          }
        })
      })


      // delTable(item.errorTestPaperId).then(res=>{
      //   if(res.code==200){
      //     this.$message({
      //       message: '删除成功',
      //       type: 'success'
      //     });
      //     this.getTableData()
      //   }
      // })
    }
  },
};
</script>
<style scoped lang="scss">
.box {
  height: 100%;
  width: 100%;
  background-color: #f1f3f8;
  padding: 15px;
  box-sizing: border-box;
  display: flex;

  .left {
    height: 100%;
    width: 400px;
    background-color: white;
    overflow: auto;

    .Ltitle {
      font-size: 16px;
      padding: 0 15px;
      line-height: 50px;
      display: flex;
      align-items: center;

      span {
        margin-right: 15px;
      }

      img {
        height: 15px;
        width: 15px;
        margin-right: 15px;
      }

      img:nth-of-type(1) {
        transform: rotateZ(90deg);
      }

      img:nth-of-type(2),
      img:nth-of-type(3) {
        opacity: 0.5;
      }
    }

    .Lline {
      height: 1px;
      background-color: #f1f3f8;
    }

    .Ltree {
      padding: 15px 0;
      height: calc(100% - 51px);
      overflow: auto;

      .el-input {
        width: 50%;
        margin-right: 8px;
      }

      ::v-deep .el-tree-node {
        padding: 5px 0;
      }
    }
  }

  .right {
    height: 100%;
    width: calc(100% - 415px);
    overflow: auto;
    margin-left: 15px;
    padding: 0 15px;
    box-sizing: border-box;

    .RForm {
      display: flex;
      align-items: center;
      height: 80px;
      padding-left: 15px;
      background-color: white;

      > .el-form {
        flex: 1;
      }

      .el-form-item {
        width: 15%;
        margin-bottom: 0;
        min-width: 100px;

        ::v-deep .el-form-item__content {
          width: 100%;
        }
      }
    }

    .rBottom {
      padding-top: 15px;
      height: calc(100% - 80px - 60px - 15px);
      overflow: auto;

      ::v-deep .el-collapse-item__header {
        height: auto;
        padding: 0 15px;
        position: relative;
      }

      .itemBottom {
        position: relative;
        height: 300px;
        min-height: max-content;
      }

      .rItem {
        height: 100px;
        background-color: white;
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;
        padding: 0 15px;

        .rItemLeft {
          display: flex;
          flex-direction: column;
          justify-content: space-evenly;

          > div:nth-of-type(1) {
            font-size: 16px;
          }

          > div:nth-of-type(2) {
            font-size: 12px;
            color: #656577;
          }

          > div:nth-of-type(3) {
            font-size: 12px;
            color: #656577;
          }
        }
      }

      .rItem:nth-last-of-type(1) {
        margin-bottom: 0px;
      }
    }
  }
}

.label {
  span {
    margin-right: 15px;
  }
}

.el-icon-edit {
  color: #f1f3f8;
}

.el-tree-node {
  .custom-tree-node {
    line-height: 30px;
  }

  > .el-tree-node__content:hover {
    .label {
      display: inline-block;
    }
  }

  .label {
    display: none;
  }
}

.is-current {
  > .el-tree-node__content:nth-of-type(1) {
    .label {
      display: inline-block;
    }
  }
}

.el-tree {
  .el-tree-node__content {
    display: block !important;
  }

  .el-tree-node__children {
    overflow: visible !important;
  }
}

::v-deep .el-tree-node > .el-tree-node__children {
  overflow: visible;
}

::v-deep .el-tree--highlight-current .el-tree-node {
  min-width: max-content;
}

::v-deep .el-dialog {
  min-width: 500px;
}

.pagination-container {
  background-color: rgba(255, 255, 255, 0);
}

.yesOrNo {
  position: absolute;
  top: 0;
  right: 0;
  height: 30px;
  padding: 0 25px;
  border-bottom-left-radius: 5px;
  border: 1px red solid;
  background-color: #ff00000f;
  text-align: center;
  line-height: 30px;
  color: red;
}

.yesOrNo1 {
  position: absolute;
  top: 0;
  right: 0;
  padding: 0 25px;
  border-bottom-left-radius: 5px;
  border: 1px green solid;
  background-color: rgba(0, 128, 0, 0.1);
  text-align: center;
  line-height: 30px;
  color: green;
}

.previewBtn {
  position: absolute;
  top: 15px;
  right: 15px;
}


.deleBtn{
  position: absolute;
  bottom: 5px;
  right: 10px;
}
</style>
